package com.moduls.interfaceFunction.quartz;

import java.sql.SQLException;
import java.util.Date;

import org.apache.ibatis.session.SqlSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.stereotype.Component;

import com.moduls.interfaceFunction.core.SqlMapper;

@Configuration
@Component
@EnableScheduling
public class InventoryQuartz {

	@Autowired
	public SqlSession sqlSessions;
	
	public void inventory_day() throws NumberFormatException, SQLException  {
		SqlMapper sqlMapper = new SqlMapper(sqlSessions);
		//库存备份
		
		//查询是否有备份(定时任务会加载两次。。。。。。。。。先用着)
		String sql_backups = "select count(1) from hx_inventory_date where date = DATE((NOW()))";
		int is_backups = Integer.valueOf(sqlMapper.public_one_scale(sql_backups));
		
		if (is_backups <= 0) {
			//1.拍照
			String sql_photo = "insert into hx_inventory_photo ( "
					+ " inventory_id,item_id,sku_id,val_names,cost_price,total_num,total_amount,qichu_price, "
					+ " qichu_num,qichu_amount,today_purchase_price,today_purchase_num,today_purchase_amount,today_order_price,today_order_num,"
					+ " today_order_amount,should_price,should_num,should_amount,real_price,real_num,real_amount,loss_price,loss_num,loss_amount"
					+ " ) "
					+ " select inventory_id, item_id,sku_id,val_names,cost_price,total_num,total_amount,qichu_price,"
					+ " qichu_num,qichu_amount,today_purchase_price,today_purchase_num,today_purchase_amount,today_order_price,today_order_num, "
					+ " today_order_amount,should_price,should_num,should_amount,real_price,real_num,real_amount,loss_price,loss_num,loss_amount"
					+ " from hx_inventory ";
			
			sqlMapper.insert(sql_photo);
			
			//2.处理数据
			//清空今天入库、今天出库
			String sql_delete = "update hx_inventory_photo set today_purchase_price = 0, today_purchase_num = 0,"
					+ " today_purchase_amount = 0,today_order_price = 0,today_order_num = 0,today_order_amount = 0 ";
			sqlMapper.update(sql_delete);
			
			//更新期初库存、应库存和实际库存为当前库存，损耗为0
			String sql_update = "update hx_inventory_photo set qichu_price = cost_price, qichu_num = total_num, qichu_amount = total_amount, "
					+ " should_price = cost_price, should_num = total_num, should_amount = total_amount,"
					+ " real_price = cost_price, real_num = total_num, real_amount = total_amount ,loss_num = 0, loss_amount = 0, loss_price = 0";
			sqlMapper.update(sql_update);
			
			//更新登记
			String sql_date = "insert into hx_inventory_date (value,date) values ('inventory',DATE(now()))";
			sqlMapper.insert(sql_date);
			
		}
		
	}

}
